<?php

namespace App\Observers;

use App\Models\Order;
use App\Models\Setting as SettingModel;
use App\Service\WxArticleData;
use Illuminate\Support\Facades\Log;

class OrderObserver
{
    public function creating(Order $order)
    {
        //检查审核状态
        $audit_switch = SettingModel::query()->firstOrCreate(['key' => 'audit_switch'], ['value' => null]);

        if (json_decode($audit_switch->value)) {
            //审核开关打开
            $order->state = Order::ORDER_STATE_AUDITING;//设置审核中状态
        } else {
            $order->state = Order::ORDER_STATE_AUDIT_WAITING;//设置待投放
        }

        try {
            $read_data = WxArticleData::get(($order->url));

            if ($read_data->code == 200) {
//            $order->current_read_num = $order->initialization_read_num = $read_data->read_num;
            } else {
                throw new \Exception($read_data->msg);
            }
            $order->expect_read_num = $order->expect_read_num + $read_data->read_num;
            return $order;

        } catch (\Exception $exception) {


            Log::error('订单创建失败：' . $exception->getMessage());
        }
    }

}
